package com.situ.web.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.web.entity.User;
import com.situ.web.service.IUserService;
import com.situ.web.service.impl.UserServiceImpl;

public class LoginServlet extends HttpServlet {
	private IUserService userService = new UserServiceImpl();
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1.获得参数
		String checkCode = req.getParameter("checkCode");
		String checkCodeSession = (String) req.getSession().getAttribute("checkCode");
		if (null == checkCode 
				|| "".equals(checkCode)
				|| (checkCode.equalsIgnoreCase(checkCodeSession) == false)) {
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
			return;
		}
		
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		
		//2.业务处理
		User user = userService.login(name, password);
		//3.转发或者重定向的跳转操作
		if (user != null) {//登录成功
		//if ("zhangsan".equals(name) && "123".equals(password)) {
			//创建Session
			HttpSession session = req.getSession();//等价于req.getSession(true)
			//把数据保存到Session域对象
			session.setAttribute("user", user);
			
			ServletContext servletContext = getServletContext();
			List<User> list = (List<User>) servletContext.getAttribute("onLineUserList");
			if (list == null) {//第一个用户登录的话这个list是null
				list = new ArrayList<>();
			}
			list.add(user);
			servletContext.setAttribute("onLineUserList", list);
			
			resp.sendRedirect(req.getContextPath() + "/pageList");
		} else {//登录失败
			resp.sendRedirect(req.getContextPath() + "/fail.html");
		}
	}
}
